package hg.demo.ehcache.service.impl;

import hg.demo.ehcache.bean.UserBean;
import hg.demo.ehcache.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final Map<String, UserBean> dbMap;
    static {
        dbMap = new HashMap<>();
    }

    @Cacheable(key = "'user-' + #name",unless = "#result == null")
    @Override
    public UserBean query(String name) {
        log.info("query(),从DB获取数据,name:{}", name);
        return dbMap.get(name);
    }

    @CacheEvict(key = "'user-*'")
    @Override
    public void insert(UserBean user) {
        dbMap.put(user.getName(), user);
    }

    @CachePut(key = "'user-' + #name")
    @Override
    public void update(UserBean user) {
        dbMap.put(user.getName(), user);
    }

    @Cacheable(keyGenerator = "cacheKeyGenerator")
    @Override
    public UserBean queryByCache(String name) {
        return query(name);
    }
}
